﻿using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using NLog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WebApiTest.ModelPlus;
using WebApiTest.Models;
using WebApiTest.Tools;

namespace WebApiTest.DAL
{
    public class NBCallbackDAL
    {
        private readonly Logger _logger = LogManager.GetCurrentClassLogger();

        /// <summary>
        /// 电信回调接口向结算表插入方法
        /// </summary>
        public Task InsertSettlementDay(DeviceData serviceData, string deviceId, DateTime eventTime)
        {
            return Task.Run(() =>
            {
                try
                {
                    using (var context = new atmk_wmdb_custum_luxiContext())
                    {
                        //取当天数据
                        var settlementDay_Today = context.SettlementDay.FirstOrDefault(m => m.CtdeviceId == deviceId && m.ReadTime.ToString("yyyy-MM-dd") == eventTime.ToString("yyyy-MM-dd"));
                        //取上一次数据（正常是昨天）
                        var settlementDay_Yesterday = context.SettlementDay.Where(m => m.CtdeviceId == deviceId && m.ReadTime.Date < eventTime.Date).OrderByDescending(m => m.ReadTime).FirstOrDefault();

                        var readString = Base64Convert.ConvertBytes(serviceData.current);
                        var readValue = BytesConvert.BitConvertInts(readString, 6).First() / 100.00;

                        if (settlementDay_Today == null)
                        {
                            var SettlementDayEntity = new SettlementDay()
                            {
                                CtdeviceId = deviceId,              //电信设备唯一标识
                                Value = readValue,                   //上报数值
                                ReadTime = eventTime,           //上报时间
                                SettlementState = 0,                //是否结算  0未结算 1已结算
                                Dosage = 0                             //用量
                            };
                            if (settlementDay_Yesterday != null )
                            {
                                double dosage = readValue - settlementDay_Yesterday.Value;
                                SettlementDayEntity.Dosage = dosage;
                            }
                            if (SettlementDayEntity.Dosage < 999)
                            {
                                context.SettlementDay.Add(SettlementDayEntity);
                            }
                        }
                        else
                        {
                            double dosage = 0;
                            if (settlementDay_Yesterday == null)
                            {
                                dosage = readValue - settlementDay_Today.Value;
                            }
                            else
                            {
                                dosage = readValue - settlementDay_Yesterday.Value;
                            }
                            settlementDay_Today.Value = readValue;
                            settlementDay_Today.Dosage = dosage;
                            settlementDay_Today.ReadTime = eventTime;
                            if (settlementDay_Today.Dosage < 999)
                            {
                                context.Update(settlementDay_Today);
                            }
                        }
                        return context.SaveChanges();
                    }
                }
                catch (Exception ex)
                {
                    _logger.Error($"InsertSettlementDay方法 上传的数据：{ JsonConvert.SerializeObject(serviceData)} deviceId:{deviceId}");
                    _logger.Error($"InsertSettlementDay方法 记录数据异常：{ex.Message}");
                    return 0;
                }
            });
        }
        /// <summary>
        /// 原始上报数据记录
        /// </summary>
        /// <param name="meterNumber"></param>
        /// <param name="serviceData"></param>
        /// <param name="eventTime"></param>
        /// <returns></returns>
        public Task MeterRecordSave(DeviceData serviceData, string deviceId, DateTime eventTime)
        {
            return Task.Run(() =>
            {
                try
                {
                    using (var context = new atmk_wmdb_custum_luxiContext())
                    {
                        //当前水表读数
                        var readString = Base64Convert.ConvertBytes(serviceData.current);
                        var readInt = BytesConvert.BitConvertInts(readString, 6).First();
                        //历史水表读数
                        var history = BytesConvert.BitConvertInts(Base64Convert.ConvertBytes(serviceData.history), 6);
                        //创建需要保存的水表数据
                        var meterReadingRecord = new MeterReadingRecord()
                        {
                            Id = Guid.NewGuid().ToString(),
                            CtdeviceId = deviceId,
                            ReadTime = eventTime,
                            Value = readInt / 100.00,
                            ValveState = serviceData.valve,
                            MsgType = serviceData.msgtype,
                            Warning = serviceData.warning,//表头 光电直读 异常报警
                            Voltage = ((serviceData.voltage + 150) * 0.01).ToString("f2"),
                            Value24 = string.Join(",", history.Select(m => m / 100)), //0未知1当前数据2冻结数据
                            CreateTime = DateTime.Now,
                        };
                        context.Add(meterReadingRecord);
                        return context.SaveChanges();
                    }
                }
                catch (Exception ex)
                {
                    _logger.Error($"MeterRecordSave 上传的数据：{ JsonConvert.SerializeObject(serviceData)} deviceId:{deviceId}");
                    _logger.Error($"MeterRecordSave 记录数据异常：{ex.Message}");
                    return 0;
                }
            });
        }

        /// <summary>
        /// 磁攻击报警记录数据
        /// </summary>
        /// <param name="serviceData"></param>
        /// <param name="meterCodeIdMap"></param>
        /// <param name="eventTime"></param>
        public Task InsertWarningMagnetism(DeviceData serviceData, string deviceId, DateTime eventTime)
        {
            return Task.Run(() =>
            {
                try
                {
                    using (var context = new atmk_wmdb_custum_luxiContext())
                    {
                        //当前水表读数
                        var readString = Base64Convert.ConvertBytes(serviceData.current);
                        var readInt = BytesConvert.BitConvertInts(readString, 6).First();
                        //历史水表读数
                        var history = BytesConvert.BitConvertInts(Base64Convert.ConvertBytes(serviceData.history), 6);

                        var warningMagnetism = new WarningMagnetism()
                        {
                            Id = Guid.NewGuid().ToString(),
                            CtdeviceId = deviceId,
                            ReadTime = eventTime,
                            Value = readInt / 100.00,
                            ValveState = serviceData.valve,
                            MsgType = serviceData.msgtype,
                            Warning = serviceData.warning,//表头 光电直读 异常报警
                            Voltage = ((serviceData.voltage + 150) * 0.01).ToString("f2"),
                            Value24 = string.Join(",", history.Select(m => m / 100)), //0未知1当前数据2冻结数据
                            CreateTime = DateTime.Now,
                        };
                        context.WarningMagnetism.Add(warningMagnetism);
                        return context.SaveChanges();
                    }
                }
                catch (Exception ex)
                {
                    _logger.Error($"InsertWarningMagnetism 磁报警记录数据异常：{ex.Message}");
                    return 0;
                }
            });
        }
    }
}
